package com.legend.ds.aop;

import com.legend.ds.config.LanzhenDynamicDataSourceContextHolder;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springblade.core.secure.utils.AuthUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;


/**
 * @Auther: tangwei
 * @Date: 2021/7/12 下午1:13
 * @Description: 类描述信息
 */
@Order(-1)
@Aspect
@Component
public class LanzhenDynamicDataSourceAspect {

    @Value("${lanzhen.ds.enable}")
    private boolean isOpen;

    @Before("execution(* *..service.*.*(..))") //确定切面入口
    public void changeDataSource(){
        if(isOpen){
            String tenantId = AuthUtil.getTenantId();
            if(tenantId == null || tenantId.equals("")){
                LanzhenDynamicDataSourceContextHolder.setDataSourceType("default"); //确定当前线程的数据源
            }else{
                LanzhenDynamicDataSourceContextHolder.setDataSourceType("tenant"+tenantId); //确定当前线程的数据源
            }
        }
    }

    @After("execution(* *..service.*.*(..))") //执行完毕之后，需要清楚当前线程使用的数据源
    public void cheanDataSource(){
        LanzhenDynamicDataSourceContextHolder.removeDataSourceRouterKey(); //清除当前线程的数据源
    }
}


